package com.base.controller;

import java.io.PrintWriter;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.base.po.voip.*;
import com.base.service.*;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.base.comm.CommContent;
import com.base.comm.CommUrls;
import com.base.po.sqlparam.RechargeablecardsExamplePage;
import com.base.utils.CardUtils;
import com.base.utils.IP;
import com.base.utils.PasswordUtils;
import com.base.utils.Produce;

/**
 * admin管理系统控制器
 * 
 * @author Administrator
 *
 */
@Log4j
@Controller
@RequestMapping("/admin")
public class content_kaika {
	@Autowired
	private RechargeablecardsService rechargeablecardsService;
	@Autowired
	private RechargeablecardsGiftService rechargeablecardsGiftService;
	@Autowired
	private FreeroutesService freeroutesService;
	@Autowired
	private UsersService usersService;
	@Autowired
	private LogsService logsService;// log日志

	// 用户首页
	@RequestMapping("/content_kaika")
	public ModelAndView index(HttpServletRequest request) throws Exception {
		// 返回ModelAndView
		ModelAndView modelAndView = new ModelAndView();
		// 获取浏览器缓存信息
		Integer adminUsergrade = (Integer) request.getSession().getAttribute("adminUsergrade");
		String adminUserId = (String) request.getSession().getAttribute("adminUserId");
		List<Users> users = null;
		if (adminUserId == null || adminUsergrade == null) {
			modelAndView.setViewName("jsp/login");
			return modelAndView;
		}
		UsersExample usersExample = new UsersExample();
		switch (adminUsergrade) {
		case 0:
			usersExample.getOredCriteria().add(usersExample.createCriteria().andDatastatusEqualTo(true));
			users = usersService.selectByExample(usersExample);
			break;

		case 1:
			usersExample.getOredCriteria().add(usersExample.createCriteria().andParentidEqualTo(adminUserId));
			users = usersService.selectByExample(usersExample);
			Users oemUser = usersService.selectByPrimaryKey(adminUserId);
			users.add(oemUser);
			break;

		default:
			modelAndView.setViewName("jsp/datanotfound");
			return modelAndView;
		}
		// 获取所有费率
		FreeroutesExample freeroutesExample = new FreeroutesExample();
		freeroutesExample.setOrderByClause("CreateTime");
		freeroutesExample.getOredCriteria().add(freeroutesExample.createCriteria().andDatastatusEqualTo(true));
		List<Freeroutes> freeroutes = freeroutesService.selectByExample(freeroutesExample);
		// 设置页面进行跳转
		request.setAttribute("today", new SimpleDateFormat("yyyy-MM-dd").format(Produce.getNowDate()));
		request.setAttribute("freeroutes", freeroutes);
		request.setAttribute("users", users);
		modelAndView.setViewName("jsp/content_kaika");
		return modelAndView;
	}

	String SUCCESS = "success";

	// 开卡
	@RequestMapping(value = "/insertCards", method = RequestMethod.POST)
	public void insertCards(HttpServletRequest request, HttpServletResponse response, Integer type, String feelroute,
			String time, Integer probationperiod, Integer money, Integer shopmoney,Integer nums, String username,
							Byte isupdateshop)
			throws Exception {
		// 返回参数
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		String adminId = (String) request.getSession().getAttribute("adminUserId");
		
		
		if(Produce.isValidDate(time) == false) {
			out.print("日期格式不正确");
			return;
		}
		 
		if (adminId == null || nums == null) {
			out.print("请刷新页面重试！");
			return;
		}
		if (nums > 10000) {
			out.print("您输入的开卡数量过大，请输入1万或者1万内的数量");
			return;
		}
		// TODO 获取有效期天数
		Integer termofvalidity = Produce.differentDays(Produce.getNowDate(), new SimpleDateFormat("yyyy-MM-dd").parse(time));
		// TODO 查询接收人信息
		if(username == null) {
			out.print("接收人不能为空");
			return;
		}
		List<Users> user = usersService.selectByUserName(username);
		String parentid = null;
		if(user !=null && user.size()>0) {
			if(user.get(0) != null) {
				parentid = user.get(0).getId();
			}else {
				out.print("该账户不存在");
				return;
			}
		}else {
			out.print("该账户不存在或者输入的账户不正确");
			return;
		}
		
		switch (type) {
		case 1:
			money = 0;
			probationperiod = 30;
			break;
		case 2:
			money = 0;
			probationperiod = 90;
			break;
		case 3:
			money = 0;
			probationperiod = 365;
			break;
		}
		Long startTime = System.currentTimeMillis();
		// 获取最新的卡
		RechargeablecardsExamplePage example = new RechargeablecardsExamplePage();
		example.pagesize = 1;
		example.rows = 1;
		example.start = 0;
		example.setOrderByClause("CardNo");
		List<Rechargeablecards> s = rechargeablecardsService.selectByExamplePage(example);
		int lastnum = 1000000;
		int lastnumber = 100000;
		String num = PasswordUtils.Getnum();
		if (s != null && s.size() > 0) {
			Rechargeablecards r = s.get(0);
			String laststr = rechargeablecardsService.selectMaxCardNo();
			lastnum = Integer.parseInt(laststr.substring(0, laststr.length() - 3));
			lastnumber = Integer.parseInt(rechargeablecardsService.selectByCardNo(laststr).get(0).getNumber());
		}
		Connection conn = null;
		PreparedStatement pstm = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection(CommUrls.JDBC, CommUrls.JDBC_USER, CommUrls.JDBC_PASSWORD);
			String sql = " insert into rechargeablecards (ID, CardNo, Pwd, " + " Money, ParentID, Status, "
					+ " TermOfValidity, ProbationPeriod, FeelRoute, " + " DataStatus, Batch, CreateTime, "
					+ " UseTime, Mobile, PicPath, " + " Type, Number,IsUpdateShop)values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
			pstm = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
			conn.setAutoCommit(false);
			//生成的卡号
			String cardno = null;
			//生成的第一张卡
			String fistCardno = null;
			//生成的最后一张卡
			String lastCardno = null;
			for (int i = 1; i <= nums; i++) {
				lastnumber += 1;
				lastnum += 1;
				pstm.setString(1, Produce.getUUID());
				cardno = String.valueOf(lastnum) + CardUtils.getRandom(100, 999);
				pstm.setString(2 , cardno);
				if(i == 1) {
					fistCardno = cardno;
				}
				if(i == nums) {
					lastCardno = cardno;
				}
				pstm.setString(3, String.valueOf(CardUtils.getRandom(123456, 987654)));
				pstm.setInt(4, money);
				pstm.setString(5, parentid);
				pstm.setInt(6, 0);
				pstm.setInt(7, termofvalidity);
				pstm.setInt(8, probationperiod);
				pstm.setString(9, feelroute);
				pstm.setBoolean(10, true);
				pstm.setString(11, num);
				pstm.setDate(12, new Date(Produce.getNowDate().getTime()));
				pstm.setDate(13, new Date(Produce.getNowDate().getTime()));
				pstm.setString(14, null);
				pstm.setString(15, null);
				pstm.setInt(16, type);
				pstm.setString(17, String.valueOf(lastnumber));
				pstm.setByte(18, isupdateshop);
				pstm.addBatch();
				if ((i + 1) % 1000 == 0) {
					pstm.executeBatch();// 每执行一次就清一次sql缓存。
					pstm.clearBatch(); // 否则每一次是执行1000，2000，3000...条sql语句而不是每一次执行1000条
				}
			}
			pstm.executeBatch();
			conn.commit();
//			out.print(SUCCESS);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			String nowTime = sdf.format(new java.util.Date());
			String usernamesys = (String) request.getSession().getAttribute("useracc");
//			logsService.insert(CommContent.TYPE_DELET_KAIKA, "成功开了" + nums + "张卡", usernamesys, true, IP.getIpAddr(request));
			Users u = usersService.selectByPrimaryKey(parentid);
			logsService.insert(CommContent.TYPE_DELET_KAIKA, "用户：" + usernamesys + "生成卡密,卡号从：" + fistCardno + "到" + lastCardno + ",数量：" + nums
					+ ",时间" + nowTime + ",到" + u.getUsername(), usernamesys, true, IP.getIpAddr(request));
			Long endTime = System.currentTimeMillis();
			System.out.println("开" + nums + "张卡成功,用时：" + (endTime - startTime) + "毫秒");

			try {
				u.setBalance(u.getBalance().subtract(new BigDecimal(nums * money)));
				usersService.updateByPrimaryKeySelective(u);
			}catch (Exception e){
				System.out.println("费用扣除失败");
			}

			if(type == 7){
				rechargeablecardsGiftService.insertSelective(new RechargeablecardsGift(Produce.getUUID(), num, shopmoney));
			}

			out.print(num);
			return;
		} catch (Exception e) {
			out.print("开发失败，请您重试");
			e.printStackTrace();
			throw new RuntimeException(e);
		} finally {
			if (pstm != null) {
				try {
					pstm.close();
				} catch (SQLException e) {
					e.printStackTrace();
					throw new RuntimeException(e);
				}
			}
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					out.print("开卡失败，请您重试");
					e.printStackTrace();
					throw new RuntimeException(e);
				}
			}
		}

	}
//	//同步代码块，保证必须每次只能允许一个用户开卡
//	private static Object lock=new Object();
	// 开卡
	@RequestMapping(value = "/insertCardsNew", method = RequestMethod.POST)
	public void insertCardsNew(HttpServletRequest request, HttpServletResponse response, Integer type, String feelroute,
							String time, Integer probationperiod, Integer money, Integer shopmoney,Integer nums, String username,
							Byte isupdateshop)
			throws Exception {

		// 返回参数
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		String adminId = (String) request.getSession().getAttribute("adminUserId");
		List<Rechargeablecards> list = new ArrayList<Rechargeablecards>();

		if(Produce.isValidDate(time) == false) {
			out.print("日期格式不正确");
			return;
		}

		if (adminId == null || nums == null) {
			out.print("请刷新页面重试！");
			return;
		}
		if (nums > 10000) {
			out.print("您输入的开卡数量过大，请输入1万或者1万内的数量");
			return;
		}
		// TODO 获取有效期天数
		Integer termofvalidity = Produce.differentDays(Produce.getNowDate(), new SimpleDateFormat("yyyy-MM-dd").parse(time));
		// TODO 查询接收人信息
		if(username == null) {
			out.print("接收人不能为空");
			return;
		}
		List<Users> user = usersService.selectByUserName(username);
		String parentid = null;
		if(user !=null && user.size()>0) {
			if(user.get(0) != null) {
				parentid = user.get(0).getId();
			}else {
				out.print("该账户不存在");
				return;
			}
		}else {
			out.print("该账户不存在或者输入的账户不正确");
			return;
		}

		switch (type) {
			case 1:
				money = 0;
				probationperiod = 30;
				break;
			case 2:
				money = 0;
				probationperiod = 90;
				break;
			case 3:
				money = 0;
				probationperiod = 365;
				break;
		}
		Long startTime = System.currentTimeMillis();
		// 获取最新的卡
		RechargeablecardsExamplePage example = new RechargeablecardsExamplePage();
		example.pagesize = 1;
		example.rows = 1;
		example.start = 0;
		example.setOrderByClause("CardNo");
		List<Rechargeablecards> s = rechargeablecardsService.selectByExamplePage(example);
		int lastnum = 1000000;
		int lastnumber = 100000;
		String num = PasswordUtils.Getnum();
		if (s != null && s.size() > 0) {
			Rechargeablecards r = s.get(0);
			String laststr = rechargeablecardsService.selectMaxCardNo();
			lastnum = Integer.parseInt(laststr.substring(0, laststr.length() - 4));
			lastnumber = Integer.parseInt(rechargeablecardsService.selectByCardNo(laststr).get(0).getNumber());
		}
		try {
			//生成的卡号
			String cardno = null;
			//生成的第一张卡
			String fistCardno = null;
			//生成的最后一张卡
			String lastCardno = null;
			int addSuccessNums = 0;
			for (int i = 0; i < nums; i++) {
				Rechargeablecards card = new Rechargeablecards();
				lastnumber += 1;
				lastnum += 1;
				card.setId(Produce.getUUID());
				cardno = String.valueOf(lastnum) + CardUtils.addZeroForNum(Integer.toString(i), 4);
//				cardno = String.valueOf(lastnum) + CardUtils.getRandom(100, 999);
				card.setCardno(cardno);
				if(i == 1) {
					fistCardno = cardno;
				}
				if(i == nums) {
					lastCardno = cardno;
				}
				card.setPwd(String.valueOf(CardUtils.getRandom(123456, 987654)));
				card.setMoney(money);
				card.setParentid(parentid);
				card.setStatus(0);
				card.setTermofvalidity(termofvalidity);
//				card.setTermofvalidityTime(time);
				card.setProbationperiod(probationperiod);
				card.setFeelroute(feelroute);
				card.setDatastatus(true);
				card.setBatch(num);
				card.setCreatetime(new Date(Produce.getNowDate().getTime()));
				card.setType(type);
				card.setNumber(String.valueOf(lastnumber));
				card.setIsupdateshop(isupdateshop);
				list.add(card);
				if (i % 50 == 0) {//每50条执行一次
					addSuccessNums += rechargeablecardsService.batchAddCards(list);
					list=null;
					list=new ArrayList<Rechargeablecards>();
				}
			}
			if (list!=null&&list.size()>0) {
				addSuccessNums += rechargeablecardsService.batchAddCards(list);
			}
//			out.print(SUCCESS);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			String nowTime = sdf.format(new java.util.Date());
			String usernamesys = (String) request.getSession().getAttribute("useracc");
//			logsService.insert(CommContent.TYPE_DELET_KAIKA, "成功开了" + nums + "张卡", usernamesys, true, IP.getIpAddr(request));
			Users u = usersService.selectByPrimaryKey(parentid);
			logsService.insert(CommContent.TYPE_DELET_KAIKA, "用户：" + usernamesys + "生成卡密,卡号从：" + fistCardno + "到" + lastCardno + ",数量：" + nums
					+ ",时间" + nowTime + ",到" + u.getUsername(), usernamesys, true, IP.getIpAddr(request));
			Long endTime = System.currentTimeMillis();
			System.out.println("开" + nums + "张卡成功,用时：" + (endTime - startTime) + "毫秒");

			try {
				u.setBalance(u.getBalance().subtract(new BigDecimal(nums * money)));
				usersService.updateByPrimaryKeySelective(u);
			}catch (Exception e){
				System.out.println("费用扣除失败");
			}

			if(type == 7){
				rechargeablecardsGiftService.insertSelective(new RechargeablecardsGift(Produce.getUUID(), num, shopmoney));
			}
			out.print(num);
			return;
		} catch (Exception e) {
			out.print("开发失败，请您重试");
			e.printStackTrace();
			throw new RuntimeException(e);
		}

	}
	// 开卡
	@RequestMapping(value = "/addCardsNew", method = RequestMethod.POST)
	public @ResponseBody
	String addCardsNew(HttpServletRequest request, Integer type,
					   String time, Integer probationperiod, Integer money, Integer nums, String username,
					   Byte isupdateshop) throws Exception {
//		Resp<AddCardRespose> resp = new Resp<AddCardRespose>();
		// 返回参数
//		response.setCharacterEncoding("utf-8");
//		response.setContentType("text/html;charset=UTF-8");
//		PrintWriter out = response.getWriter();
		String adminId = (String) request.getSession().getAttribute("adminUserId");
		Integer adminUsergrade = (Integer) request.getSession().getAttribute("adminUsergrade");

		if (type==null||type<1||type>8) {
//			resp = resp.error(Resp.Status.PARAM_ERROR ,"卡类型错误");
			return "卡类型错误";
		}

		if (time==null||!Produce.isValidDate(time)) {
//			resp = resp.error(Resp.Status.PARAM_ERROR ,"充值有效期错误");
			return "充值有效期错误";
		}
		// TODO 获取有效期天数
		Integer termofvalidity = null;
		try {
			termofvalidity = Produce.differentDays(Produce.getNowDate(), new SimpleDateFormat("yyyy-MM-dd").parse(time));
		} catch (Exception e) {
//			resp = resp.error(Resp.Status.PARAM_ERROR ,"请输入正确的有效期");
			return "请输入正确的有效期";
		}
		if (probationperiod==null||probationperiod<1) {
			probationperiod = 360;
		}

		if (money==null||money<1||money>1000000) {
//			resp = resp.error(Resp.Status.PARAM_ERROR ,"面值错误");
			return "面值错误";
		}

		if (nums == null||nums<1) {
//			resp = resp.error(Resp.Status.PARAM_ERROR ,"请输入开卡数量");
			return "请输入开卡数量";
		}

		if (nums > 10000) {
//			resp = resp.error(Resp.Status.PARAM_ERROR ,"您输入的开卡数量过大，请输入1万或者1万内的数量");
			return "您输入的开卡数量过大，请输入1万或者1万内的数量";
		}
		if (adminId == null) {
//			resp = resp.error(Resp.Status.NO_LOGIN ,"未登录或登录失效");
			return "未登录或登录失效";
		}

		// TODO 查询接收人信息
		if(username == null) {
//			resp = resp.error(Resp.Status.PARAM_ERROR ,"请输入接收人");
			return "请输入接收人";
		}
		List<Users> user = usersService.selectByUserName(username);
		String parentid = null;
		if(user !=null && user.size()>0) {
			parentid = user.get(0).getId();
		}else {
//			resp = resp.error(Resp.Status.PARAM_ERROR ,"接收人账户不存在");
			return "接收人账户不存在";
		}

		if (adminUsergrade==null||!adminUsergrade.equals(1)) {
//			resp = resp.error(Resp.Status.NO_ACCESS ,"对不起,您没有开发权限");
			return "对不起,您没有开发权限";
		}


		Long startTime = System.currentTimeMillis();
		// 获取最新的卡  batchAddCards
		RechargeablecardsExamplePage example = new RechargeablecardsExamplePage();
		example.pagesize = 1;
		example.rows = 1;
		example.start = 0;
		example.setOrderByClause("CardNo");
		List<Rechargeablecards> s = rechargeablecardsService.selectByExamplePage(example);
		int lastnum = 1000000;
		int lastnumber = 100000;
		String num = PasswordUtils.Getnum();
		if (s != null && s.size() > 0) {
			Rechargeablecards r = s.get(0);
			String laststr = r.getCardno();
			lastnum = Integer.parseInt(laststr.substring(0, laststr.length() - 3));
			lastnumber = Integer.parseInt(r.getNumber());
		}

		List<Rechargeablecards> list = new ArrayList<Rechargeablecards>();

		//生成的卡号
		String cardno = null;
		//生成的第一张卡
		String fistCardno = null;
		//生成的最后一张卡
		String lastCardno  = null;
		int addSuccessNums = 0;
		for (int i = 1; i <= nums; i++) {
			Rechargeablecards card = new Rechargeablecards();
			lastnumber += 1;
			lastnum += 1;
			card.setId(Produce.getUUID());
			cardno = String.valueOf(lastnum) + CardUtils.getRandom(100, 999);
			card.setCardno(cardno);
			if(i == 1) {
				fistCardno = cardno;
			}
			if(i == nums) {
				lastCardno = cardno;
			}
			card.setPwd(String.valueOf(CardUtils.getRandom(123456, 987654)));
			card.setMoney(money);
			card.setParentid(parentid);
			card.setStatus(0);
			card.setTermofvalidity(termofvalidity);
//			card.setTermofvalidityTime(time);
			card.setProbationperiod(probationperiod);
			card.setFeelroute("0.25");
			card.setDatastatus(true);
			card.setBatch(num);
			card.setCreatetime(new Date(Produce.getNowDate().getTime()));
			card.setType(type);
			card.setNumber(String.valueOf(lastnumber));
			card.setIsupdateshop(isupdateshop);
			list.add(card);
			if (i % 50 == 0) {//每50条执行一次
				addSuccessNums += rechargeablecardsService.batchAddCards(list);
				list=null;
				list=new ArrayList<Rechargeablecards>();
			}
		}
		if (list!=null&&list.size()>0) {
			addSuccessNums += rechargeablecardsService.batchAddCards(list);
		}

//		AddCardRespose cardRespose = new AddCardRespose();
//		cardRespose.setApplyNum(nums);
//		cardRespose.setSuccessNum(addSuccessNums);
//		cardRespose.setCardFrom(Integer.parseInt(fistCardno));
//		cardRespose.setCardTo(Integer.parseInt(lastCardno));
//
//		resp = resp.successSub(cardRespose, "制卡成功");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		String nowTime = sdf.format(new java.util.Date());
		String usernamesys = (String) request.getSession().getAttribute("useracc");
//			logsService.insert(CommContent.TYPE_DELET_KAIKA, "成功开了" + nums + "张卡", usernamesys, true, IP.getIpAddr(request));
		Users u = usersService.selectByPrimaryKey(parentid);
		logsService.insert(CommContent.TYPE_DELET_KAIKA, "用户：" + usernamesys + "生成卡密,卡号从：" + fistCardno + "到" + lastCardno + ",制卡数量：" + nums
				+ ",成功数量："+addSuccessNums+",时间" + nowTime + ",到" + u.getUsername(), usernamesys, true, IP.getIpAddr(request));
		Long endTime = System.currentTimeMillis();
		System.out.println("开" + nums + "张卡成功,用时：" + (endTime - startTime) + "毫秒");

		try {
			u.setBalance(u.getBalance().subtract(new BigDecimal(nums * money)));
			usersService.updateByPrimaryKeySelective(u);
		}catch (Exception e){
			System.out.println("费用扣除失败");
		}

		if(type == 7){
			rechargeablecardsGiftService.insertSelective(new RechargeablecardsGift(Produce.getUUID(), num, nums * money));
		}

		return "开卡成功";
	}

}
